<?php

namespace app\task\controller;

use app\merchant\model\MerchantModel;
use app\task\model\CategoryModel;
use app\task\model\TaskModel;
use app\task\model\TransportModel;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\service\AdminService;
use think\facade\Db;

/**
 * 订单任务管理
 * @class Task
 * @package app\task\controller
 */
class Task extends Controller
{
    /**
     * 订单任务列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
        $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
        $this->task_status_dict = TaskModel::TASK_STATUS_DICT;
        $this->title = '订单任务列表';
        TaskModel::mQuery()->alias('t')->where('t.is_deleted', 0)
            ->with(['category','merchant', 'transport'])
            ->field('t.*')
            ->join('task_category tc', 'tc.id=t.category_id', 'left')
            ->join('merchant m', 'm.id=t.merchant_id', 'left')
            ->join('task_transport tr', 'tr.task_id=t.id', 'left')
            ->like('t.name#name,tr.type#transport_type,tr.scene#transport_scene')
            ->equal('t.task_status#task_status,t.category_id#category_id,t.merchant_id#merchant_id')
            ->dateBetween('t.create_at#create_at,t.exec_at#exec_at')
            ->layTable();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$vo){
            if(isset($vo['task_status'])) $vo['task_status_text'] = TaskModel::TASK_STATUS_DICT[$vo['task_status']] ?? '';
         }
    }

    /**
     * 订单任务详情
     * @auth true
     */
    public function detail()
    {
        $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
        $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
        $task = TaskModel::with('transport')->where('id', $this->request->get('id'))->find()->toArray();
        if ($task['category_id'] == 1){
            $transport = $task['transport'];
            $task['start_at'] = $transport['start_at'] ?? '';
            $task['end_at'] = $transport['end_at'] ?? '';
            $task['transport_type'] = $transport['type'] ?? '';
            $task['transport_scene'] = $transport['scene'] ?? '';
            $task['transport_distance'] = $transport['distance'] ?? '';
            $task['weight'] = $transport['weight'] ?? '';
            $task['province'] = $transport['province'] ?? '';
            $task['city'] = $transport['city'] ?? '';
            $task['area'] = $transport['area'] ?? '';
            $task['address'] = $transport['address'] ?? '';
            $task['place'] = $transport['place'] ?? '';
            $task['lat'] = $transport['lat'] ?? '';
            $task['lng'] = $transport['lng'] ?? '';
            $task['latlng'] = $transport['latlng'] ?? '';
            $task['province2'] = $transport['province2'] ?? '';
            $task['city2'] = $transport['city2'] ?? '';
            $task['area2'] = $transport['area2'] ?? '';
            $task['address2'] = $transport['address2'] ?? '';
            $task['place2'] = $transport['place2'] ?? '';
            $task['lat2'] = $transport['lat2'] ?? '';
            $task['lng2'] = $transport['lng2'] ?? '';
            $task['latlng2'] = $transport['latlng2'] ?? '';
            $task['transport_type_other'] = $transport['type_other'] ?? '';
            $task['transport_scene_other'] = $transport['scene_other'] ?? '';
        }
        $this->vo = $task;
        $this->fetch();
    }

    /**
     * 添加订单任务
     * @auth true
     */
    public function add()
    {
//        $this->_applyFormToken();
        TaskModel::mForm('form');
    }

    /**
     * 编辑订单任务
     * @auth true
     */
    public function edit()
    {
//        $this->_applyFormToken();
        TaskModel::mForm('form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {
            $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
            $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
            $area_list = Db::name('Area')->order('id asc')->column('id,pid,ext_name as name');
            $this->area_list = DataExtend::arr2tree($area_list, 'id', 'pid','children');
            $this->transport_distance_list_obj = get_transport_distance_list_obj();
            // 存在merchant_id
            if (empty($vo) && !empty($this->request->get('merchant_id'))){
                $vo['merchant_id'] = $this->request->get('merchant_id');
            }
            if(!empty($this->request->get('id'))){
                $task = TaskModel::with('transport')->where('is_deleted', 0)->where('id', $this->request->get('id'))->find()->toArray();
                if ($task['category_id'] == 1){
                    $transport = $task['transport'];
                    $task['start_at'] = $transport['start_at'] ?? '';
                    $task['end_at'] = $transport['end_at'] ?? '';
                    $task['transport_type'] = $transport['type'] ?? '';
                    $task['transport_scene'] = $transport['scene'] ?? '';
                    $task['transport_distance'] = $transport['distance'] ?? '';
                    $task['weight'] = $transport['weight'] ?? '';
                    $task['province'] = $transport['province'] ?? '';
                    $task['city'] = $transport['city'] ?? '';
                    $task['area'] = $transport['area'] ?? '';
                    $task['address'] = $transport['address'] ?? '';
                    $task['place'] = $transport['place'] ?? '';
                    $task['lat'] = $transport['lat'] ?? '';
                    $task['lng'] = $transport['lng'] ?? '';
                    $task['latlng'] = $transport['latlng'] ?? '';
                    $task['province2'] = $transport['province2'] ?? '';
                    $task['city2'] = $transport['city2'] ?? '';
                    $task['area2'] = $transport['area2'] ?? '';
                    $task['address2'] = $transport['address2'] ?? '';
                    $task['place2'] = $transport['place2'] ?? '';
                    $task['lat2'] = $transport['lat2'] ?? '';
                    $task['lng2'] = $transport['lng2'] ?? '';
                    $task['latlng2'] = $transport['latlng2'] ?? '';
                    $task['transport_type_other'] = $transport['type_other'] ?? '';
                    $task['transport_scene_other'] = $transport['scene_other'] ?? '';
                }
                $vo = $task;
            }else{
                $vo['category_id'] =  1;
            }
        } else {
            if (isset($vo['id'])){
                $id = $this->request->post('id');
                $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
                if (empty($task)) $this->error('订单任务不存在');
                if ($task->task_status != TaskModel::TASK_STATUS__PENDING_REVIEW) $this->error('待审核的订单任务才能被修改');
            }
            if (empty($vo['province']) || empty($vo['city']) || empty($vo['area'])) $this->error('请选择省市区');

//            if ($vo['category_id'] == 1){
//                $vo['exec_at'] =  $vo['start_at'];
//                // 验证数据
//                if (empty($vo['province2']) || empty($vo['city2']) || empty($vo['area2'])) $this->error('请选择省市区');
//            }

            $vo['place'] = $vo['province'].$vo['city'].$vo['area'].$vo['address'];
            $vo['money'] = floatval($vo['money']);
            [$vo['lat'], $vo['lng']] = explode(',', $vo['latlng']);
            $vo['task_status'] = TaskModel::TASK_STATUS__PENDING_REVIEW;
            $vo['file_name'] = '审批文件';
            if (empty($vo['file'])) $this->error('请上传审批文件');

            // 是否可以转换为整数的值
            if (filter_var($vo['weight'], FILTER_VALIDATE_INT) === false) $this->error('预估重量格式不正确');
            $vo['weight'] = intval($vo['weight']);
            if ($vo['weight'] > 1000000) $this->error('预估重量不大于1000000');
        }
    }

    protected function _form_result(bool $res, array $data){
        if (!$res) return true;
        // 创建货运相关信息
        if ($data['category_id'] == 1){
            $vo = $this->request->post();
            $transport = TransportModel::where('task_id', $data['id'])->findOrEmpty();
            $vo['place'] = $vo['province'].$vo['city'].$vo['area'].$vo['address'];
            [$vo['lat'], $vo['lng']] = explode(',', $vo['latlng']);
//            $vo['place2'] = $vo['province2'].$vo['city2'].$vo['area2'].$vo['address2'];
//            [$vo['lat2'], $vo['lng2']] = explode(',', $vo['latlng2']);
            $transport->save([
                'task_id' => $data['id'],
//                'start_at' => $vo['start_at'],
//                'end_at' => $vo['end_at'],
                'type' => $vo['transport_type'],
                'scene' => $vo['transport_scene'],
                'distance' => $vo['transport_distance'],
                'weight' => $vo['weight'],
                'province' => $vo['province'],
                'city' => $vo['city'],
                'area' => $vo['area'],
                'address' => $vo['address'],
                'place' => $vo['place'],
                'lat' => $vo['lat'],
                'lng' => $vo['lng'],
                'latlng' => $vo['latlng'],
//                'province2' => $vo['province2'],
//                'city2' => $vo['city2'],
//                'area2' => $vo['area2'],
//                'address2' => $vo['address2'],
//                'place2' => $vo['place2'],
//                'lat2' => $vo['lat2'],
//                'lng2' => $vo['lng2'],
//                'latlng2' => $vo['latlng2'],
                'type_other' => $vo['transport_type'] == '其他' ? $vo['transport_type_other'] : '',
                'scene_other' => $vo['transport_scene'] == '其他' ? $vo['transport_scene_other'] : '',
            ]);
        }
    }

    /**
     * 修改订单任务状态
     * @auth true
     */
    public function state()
    {
        TaskModel::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除订单任务
     * @auth true
     */
//    public function remove()
//    {
//        TaskModel::mDelete();
//    }

    /**
     * 审核订单任务
     * @auth true
     */
    public function review()
    {
        if ($this->request->isGet()){
            $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
            $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
            $task = TaskModel::with('transport')->where('is_deleted', 0)->where('id', $this->request->get('id'))->find()->toArray();
            if (empty($task)) $this->error('订单任务不存在');
            if (empty($task['file'])) $this->error('请先在“编辑”操作中上传审批文件');
            if ($task['category_id'] == 1){
                $transport = $task['transport'];
                $task['start_at'] = $transport['start_at'] ?? '';
                $task['end_at'] = $transport['end_at'] ?? '';
                $task['transport_type'] = $transport['type'] ?? '';
                $task['transport_scene'] = $transport['scene'] ?? '';
                $task['transport_distance'] = $transport['distance'] ?? '';
                $task['weight'] = $transport['weight'] ?? '';
                $task['province'] = $transport['province'] ?? '';
                $task['city'] = $transport['city'] ?? '';
                $task['area'] = $transport['area'] ?? '';
                $task['address'] = $transport['address'] ?? '';
                $task['place'] = $transport['place'] ?? '';
                $task['lat'] = $transport['lat'] ?? '';
                $task['lng'] = $transport['lng'] ?? '';
                $task['latlng'] = $transport['latlng'] ?? '';
                $task['province2'] = $transport['province2'] ?? '';
                $task['city2'] = $transport['city2'] ?? '';
                $task['area2'] = $transport['area2'] ?? '';
                $task['address2'] = $transport['address2'] ?? '';
                $task['place2'] = $transport['place2'] ?? '';
                $task['lat2'] = $transport['lat2'] ?? '';
                $task['lng2'] = $transport['lng2'] ?? '';
                $task['latlng2'] = $transport['latlng2'] ?? '';

                $task['transport_type_other'] = $transport['type_other'] ?? '';
                $task['transport_scene_other'] = $transport['scene_other'] ?? '';
            }
            $this->vo = $task;
            $this->fetch();
        }else{
            $id = $this->request->post('id');
            $task_status = $this->request->post('task_status');
            $review_reason = $this->request->post('review_reason');
            $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($task)) $this->error('订单任务不存在');
            if ($task->task_status != TaskModel::TASK_STATUS__PENDING_REVIEW) $this->error('待审核的订单任务才能审核');
            if (!in_array($task_status, [TaskModel::TASK_STATUS__PENDING_ACCEPTANCE, TaskModel::TASK_STATUS__REVIEW_FAILED])) $this->error('审核状态不正确');
            if ($task_status == TaskModel::TASK_STATUS__REVIEW_FAILED && empty($review_reason)) $this->error('请填写审核不通过的原因');
            TaskModel::mSave([
                'id' => $id,
                'task_status' => $task_status,
                'review_reason' => $review_reason,
                'review_at' => date('Y-m-d H:i:s'),
                'review_admin_id' => AdminService::getUserId(),
            ]);
        }
    }

    /**
     * 取消订单任务
     * @auth true
     */
    public function cancel()
    {
        if ($this->request->isGet()){
            $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
            $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
            $task = TaskModel::with('transport')->where('is_deleted', 0)->where('id', $this->request->get('id'))->find();
            if ($task['category_id'] == 1){
                $transport = $task['transport'];
                $task['start_at'] = $transport['start_at'] ?? '';
                $task['end_at'] = $transport['end_at'] ?? '';
                $task['transport_type'] = $transport['type'] ?? '';
                $task['transport_scene'] = $transport['scene'] ?? '';
                $task['transport_distance'] = $transport['distance'] ?? '';
                $task['weight'] = $transport['weight'] ?? '';
                $task['province'] = $transport['province'] ?? '';
                $task['city'] = $transport['city'] ?? '';
                $task['area'] = $transport['area'] ?? '';
                $task['address'] = $transport['address'] ?? '';
                $task['place'] = $transport['place'] ?? '';
                $task['lat'] = $transport['lat'] ?? '';
                $task['lng'] = $transport['lng'] ?? '';
                $task['latlng'] = $transport['latlng'] ?? '';
                $task['province2'] = $transport['province2'] ?? '';
                $task['city2'] = $transport['city2'] ?? '';
                $task['area2'] = $transport['area2'] ?? '';
                $task['address2'] = $transport['address2'] ?? '';
                $task['place2'] = $transport['place2'] ?? '';
                $task['lat2'] = $transport['lat2'] ?? '';
                $task['lng2'] = $transport['lng2'] ?? '';
                $task['latlng2'] = $transport['latlng2'] ?? '';

                $task['transport_type_other'] = $transport['type_other'] ?? '';
                $task['transport_scene_other'] = $transport['scene_other'] ?? '';
            }
            $this->vo = $task;
            $this->fetch();
        }else{
            $id = $this->request->post('id');
            $cancel_reason = $this->request->post('cancel_reason');
            $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($task)) $this->error('订单任务不存在');
            if ($task->task_status != TaskModel::TASK_STATUS__PENDING_ACCEPTANCE) $this->error('待接单的订单任务才能取消');
            if (empty($cancel_reason)) $this->error('请填写取消的原因');
            TaskModel::mSave([
                'id' => $id,
                'task_status' => TaskModel::TASK_STATUS__CANCELED,
                'cancel_reason' => $cancel_reason,
                'cancel_at' => date('Y-m-d H:i:s'),
                'cancel_admin_id' => AdminService::getUserId(),
            ]);
        }
    }
}
